/**
 * 
 */
package org.destiny.account.richclient.binding;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

import org.destiny.account.entity.Customer;
import org.springframework.binding.form.FormModel;
import org.springframework.richclient.form.binding.support.AbstractBinding;

/**
 * @author kunrey_lew
 * 
 */
public class RadioGroupBinding extends AbstractBinding implements PropertyChangeListener, ActionListener {

	private JRadioButton maleRadio;
	private JRadioButton femaleRadio;

	public RadioGroupBinding(FormModel formModel, String formPropertyPath) {
		super(formModel, formPropertyPath, Integer.class);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.springframework.richclient.form.binding.support.AbstractBinding#
	 * doBindControl()
	 */
	@Override
	protected JComponent doBindControl() {

		JPanel pane = new JPanel(new FlowLayout(FlowLayout.LEFT));
		maleRadio = new JRadioButton("男性", true);
		femaleRadio = new JRadioButton("女性");
		ButtonGroup buttonGroup = new ButtonGroup();
		buttonGroup.add(maleRadio);
		buttonGroup.add(femaleRadio);
		pane.add(maleRadio);
		pane.add(femaleRadio);

		getValueModel().addValueChangeListener(this);
		maleRadio.addActionListener(this);
		femaleRadio.addActionListener(this);

		refreshControl((Integer) getValue());

		return pane;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.springframework.richclient.form.binding.support.AbstractBinding#
	 * enabledChanged()
	 */
	@Override
	protected void enabledChanged() {
		boolean enable = !isReadOnly() && isEnabled();
		maleRadio.setEnabled(enable);
		femaleRadio.setEnabled(enable);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.springframework.richclient.form.binding.support.AbstractBinding#
	 * readOnlyChanged()
	 */
	@Override
	protected void readOnlyChanged() {
		enabledChanged();
	}

	public void propertyChange(PropertyChangeEvent event) {
		refreshControl((Integer) event.getNewValue());
	}

	private void refreshControl(Integer gender) {
		if (gender != null) {
			if (gender == Customer.GENDER_MALE)
				maleRadio.setSelected(true);
			else if (gender == Customer.GENDER_FEMALE)
				femaleRadio.setSelected(true);
			else
				throw new IllegalArgumentException("gender must be one of Customer.GENDER_MALE,Customer.GENDER_FEMALE");
		}
	}

	private void refreshModel() {
		if (maleRadio.isSelected())
			getValueModel().setValueSilently(Customer.GENDER_MALE, RadioGroupBinding.this);
		else
			getValueModel().setValueSilently(Customer.GENDER_FEMALE, RadioGroupBinding.this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		refreshModel();
	}

}
